<template>
  <h1>登录页面</h1>
  <el-card style="width: 450px;margin: 0 auto;padding: 20px 10px 0 0">
    <el-form label-width="60px">
      <el-form-item label="用户">
        <el-input placeholder="请输入用户名" v-model="user.username"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input placeholder="请输入密码" show-password v-model="user.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 100%" @click="login()">登录</el-button>
      </el-form-item>
    </el-form>
  </el-card>

</template>


<script setup>
import {ref} from 'vue';
import qs from 'qs';
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";
//1.创建用户对象
const user = ref({username:'',password:''});
//2.创建登录方法
const login=()=>{
  //3.将user对象转为查询字符串格式
  let data = qs.stringify(user.value);
  console.log(data);
  // 4.给后端发请求
  axios.post('http://localhost:8080/v1/users/login',data).then(
      (res)=>{
        console.log(res);
        if (res.data.code==2002){
          let user = res.data.data;
          ElMessage.success('登陆成功!欢迎'+user.nickname+'回来');
          // localStorage以字符串键值对的方式管理数据,我们可以将登录成功的用户信息存入,方便其他地方使用
          // user是JS对象,不是字符串,所以需要先转换成字符串再存入JSON.stringfy(user)
          localStorage.setItem('user',JSON.stringify(user));
          router.push('/');
        }else{
          ElMessage.error(res.data.msg);
        }
      }
  )
}

</script>


<style scoped>

</style>